package cn.jbolt.wechat.admin.config;

import cn.hutool.core.io.FileUtil;
import cn.jbolt.core.api.JBoltApiBaseController;
import cn.jbolt.core.api.httpmethod.JBoltHttpPost;
import cn.jbolt.core.permission.CheckPermission;
import cn.jbolt.core.permission.UnCheckIfSystemAdmin;
import cn.jbolt.core.util.JBoltRealUrlUtil;
import cn.jbolt.wechat.common.WechatConfigKey;
import cn.jbolt.wechat.common.WechatMpinfoType;
import cn.jbolt.wechat.common.WechatApiResult;
import cn.jbolt.wechat.common.mp.WechatMpContext;
import cn.jbolt.wechat.model.WechatConfig;
import cn.jbolt.wechat.model.WechatMpinfo;
import cn.jbolt.wechat.permission.WechatPermissionKey;
import cn.jbolt.wechat.service.JBoltWechatConfigService;
import cn.jbolt.wechat.service.JBoltWechatMpinfoService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.JFinal;
import com.jfinal.core.Path;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;

import java.util.List;

/**
 * 微信公众平台配置
 *
 * @ClassName: WechatConfigAdminController
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2019年5月12日 下午8:35:23
 */
@UnCheckIfSystemAdmin
@CheckPermission(WechatPermissionKey.WECHAT_MPINFO)
@Path("/api/admin/wechatConfig")
public class WechatConfigAdminController extends JBoltApiBaseController {
    @Inject
    private JBoltWechatMpinfoService wechatMpinfoService;
    @Inject
    private JBoltWechatConfigService service;

    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_BASEMGR)
    public void baseMgr() {
        Long mpId = getLong(0);
        List<WechatConfig> configs = service.checkAndInitConfig(mpId, WechatConfig.TYPE_BASE);
        renderJBoltApiSuccessWithData(configs);
    }

    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_BASEMGR)
    @Before(Tx.class)
    @JBoltHttpPost
    public void submitBaseConfig(@Para("mpId") Long mpId) {

        submitConfig(WechatConfig.TYPE_BASE, mpId, getJSONList("configs", WechatConfig.class));

    }

    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_EXTRAMGR)
    public void extraMgr() {
        Long mpId = getLong(0);
        List<WechatConfig> configs = service.checkAndInitConfig(mpId, WechatConfig.TYPE_EXTRA);
        for (WechatConfig config : configs) {
            if (config.getConfigKey().equals(WechatConfigKey.MUSIC_POST_MEDIAID) && isOk(config.getConfigValue())) {
                String value = JFinal.me().getConstants().getBaseUploadPath() + "/wechatconfig/musicpost/" + config.getConfigValue() + ".jpg";
                config.put("imgUrl", JBoltRealUrlUtil.getWechatImage(value));
            }
        }
        renderJBoltApiSuccessWithData(configs);
    }

    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_EXTRAMGR)
    @Before(Tx.class)
    public void submitExtraConfig(@Para("mpId") Long mpId) {
        submitConfig(WechatConfig.TYPE_EXTRA, mpId, getJSONList("configs", WechatConfig.class));

    }


    /**
     * 上传图片到微信素材库
     */
    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_BASEMGR)
    public void uploadWechatMusicImgMedia() {
        UploadFile file = getFile("file", "wechatconfig/musicpost");
        if (notImage(file)) {
            renderJBoltApiFail("请上传图片类型文件");
            return;
        }
        Long mpId = getLong(0);
        String appId = service.getWechatConfigAppId(mpId);
        if (notOk(appId)) {
            renderJBoltApiFail("当前操作微信公众平台，配置异常：APPID");
            return;
        }

        WechatMpContext.switchTo(appId);

        try {
            WechatApiResult<WxMpMaterialUploadResult> res = WechatMpContext.uploadPermanentMaterial(WxConsts.MediaFileType.IMAGE, file.getFile());
            if (res.isSuccess() == false) {
                renderJBoltApiSuccessWithData(res.getMsg());
                return;
            }
            String mediaId = res.getData().getMediaId();
            FileUtil.rename(file.getFile(), mediaId + ".jpg", false, true);
            renderJBoltApiSuccessWithData(mediaId);

        } finally {
            WechatMpContext.switchOver();
        }

    }


    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_PAYMGR)
    public void payMgr() {
        Long mpId = getLong(0);
        List<WechatConfig> configs = service.checkAndInitConfig(mpId, WechatConfig.TYPE_PAY);
        renderJBoltApiSuccessWithData(configs);
    }

    @CheckPermission(WechatPermissionKey.WECHAT_CONFIG_PAYMGR)
    @Before(Tx.class)
    public void submitPayConfig(@Para("mpId") Long mpId) {
        submitConfig(WechatConfig.TYPE_PAY, mpId, getJSONList("configs", WechatConfig.class));
    }

    private void submitConfig(int type, Long mpId, List<WechatConfig> configs) {
        WechatMpinfo mpinfo = wechatMpinfoService.findById(mpId);
        if (mpinfo == null) {
            renderJsonFail("微信公众平台信息不存在");
            return;
        }
        if (type == WechatConfig.TYPE_EXTRA) {
            if (!mpinfo.getEnable()) {
                renderJsonFail("请在启用状态下操作更新此配置");
                return;
            }

        } else {
            if (mpinfo.getEnable() != null && mpinfo.getEnable()) {
                renderJsonFail("微信公众平台启用时无法更新配置信息，请在非启用状态下操作");
                return;
            }
        }


        boolean isWxa = mpinfo.getType().intValue() == WechatMpinfoType.XCX.getValue();
        renderJBoltApiRet(service.updateConfigs(mpId, type, isWxa, configs));
    }

}
